package pool;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @projectName: JUC
 * @package: pool
 * @className: poolDemo
 * @author: 冷环渊 doomwatcher
 * @description: TODO
 * @date: 2022/3/2 21:32
 * @version: 1.0
 */
//Executors 工具类 三大方法
/*
 *  new ThreadPoolExecutor.AbortPolicy()  银行的人满了 这种方式就是 不处理 抛出异常
 *  new ThreadPoolExecutor.CallerRunsPolicy() 银行人满了，哪里来的去哪里，回到调用线程输出，不会异常
 *  new ThreadPoolExecutor.DiscardPolicy()  队列满了 就抛出全部任务，
 *  new ThreadPoolExecutor.DiscardOldestPolicy() 尝试和最早的线程竞争 查看是否有位置，没有就抛出任务
 * */
public class poolDemo {
    public static void main(String[] args) {
        ThreadPoolExecutor threadpool = new ThreadPoolExecutor(
                2,
                5,
                3,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardOldestPolicy()
        );


        //单个线程
        //ExecutorService Threadpool = Executors.newSingleThreadExecutor();
        // 创建一个固定的线程池大小
        //ExecutorService Threadpool = Executors.newFixedThreadPool(5);
        //可以伸缩的 遇强则强
        // ExecutorService Threadpool = Executors.newCachedThreadPool();

        try {
            //最大承载如何计算 ： 阻塞队列+max数量
            //超过的话就会 爆出异常 :RejectedExecutionException
            for (int i = 1; i <= 15; i++) {
                threadpool.execute(() -> {
                    System.out.println(Thread.currentThread().getName() + "=> ok");
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //线程池使用完毕 一定要关闭
            threadpool.shutdown();
        }
    }
}
